package com.biubiu.firefly.wallpaper.firefly;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Handler;
import android.service.wallpaper.WallpaperService;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.SurfaceHolder;

import com.biubiu.firefly.R;

import java.util.ArrayList;
import java.util.List;

public class FireFlyWallpaperService extends WallpaperService {

    @Override
    public Engine onCreateEngine() {
        return new MyEngine(this);
    }


    class MyEngine extends  Engine {
        private Context mContext;
        private boolean mVisible;
        private List<FireFly> fireFlyList;
        private Handler mHandler = new Handler();
        private int heightPixels;
        private int widthPixels;
        // 记录当前用户动作发生的位置
        private float mTouchX = -1;
        private float mTouchY = -1;
        // 定义画笔
        private float strokeWidth = 0.5f;//每圈光晕宽度，模糊效果0-1
        private int count = 20;//萤火虫数量

        private Runnable mRunnable = new Runnable() {
            @Override
            public void run() {
                mHandler.removeCallbacks(mRunnable);
                drawShapeDrawable();
                mHandler.postDelayed(mRunnable,12);
            }
        };

        public MyEngine(Context context) {
            this.mContext = context;
        }

        @Override
        public void onCreate(SurfaceHolder surfaceHolder) {
            super.onCreate(surfaceHolder);
            // 设置壁纸的触碰事件为true
            setTouchEventsEnabled(true);
            fireFlyList = new ArrayList<>();
            for(int i=0;i<count;i++){
                fireFlyList.add(new FireFly(mContext));
            }

            DisplayMetrics displayMetrics = mContext.getResources().getDisplayMetrics();
            heightPixels = displayMetrics.heightPixels;
            widthPixels = displayMetrics.widthPixels;
        }


        @Override
        public void onVisibilityChanged(boolean visible) {
            super.onVisibilityChanged(visible);
            mVisible = visible;
            if (visible) {
                mHandler.post(mRunnable);
            } else {
                mHandler.removeCallbacks(mRunnable);
            }
        }

        //获取SurfaceHolder时调用
        @Override
        public SurfaceHolder getSurfaceHolder() {
            return super.getSurfaceHolder();
        }

        //手势移动时回调，onOffsetsChanged要注意一下，还记得有的手机滑动桌面时候背景图片会跟着左右移动吗，
        // 这个方法就可以实现这个效果，在手势滑动的每一帧都会回调依次。
        /**
         * @param xOffset      x方向滑动的百分比（与桌面分页数有关）
         * @param yOffset      y方向滑动百分比（一般用不到）
         * @param xOffsetStep  x方向每个分页所占的百分比（1 / xOffsetStep = 桌面的分页数）
         * @param yOffsetStep  同理
         * @param xPixelOffset x放下像素偏移量
         * @param yPixelOffset 同理
         */
        @Override
        public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) {
            super.onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixelOffset, yPixelOffset);
        }

        //Surface创建时回调
        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
        }

        //Surface销毁时回调
        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            mHandler.removeCallbacks(mRunnable);
        }

        @Override
        public void onTouchEvent(MotionEvent event) {
            /*if (event.getAction() == MotionEvent.ACTION_DOWN) {
                mTouchX = event.getX();
                mTouchY = event.getY();
            }else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                // 检测到滑动操作
                mTouchX = event.getX();
                mTouchY = event.getY();
                initLeft = mTouchX-(initRadius + initRadius/5*strokeWidth)/2;
                initTop = mTouchY-(initRadius + initRadius/5*strokeWidth)/2;
                drawShapeDrawable();
            }else if (event.getAction() == MotionEvent.ACTION_UP) {
                mTouchX = event.getX();
                mTouchY = event.getY();
                initLeft = mTouchX-(initRadius + initRadius/5*strokeWidth)/2;
                initTop = mTouchY-(initRadius + initRadius/5*strokeWidth)/2;
                drawShapeDrawable();
            }*/
            super.onTouchEvent(event);
        }

        private void drawShapeDrawable() {
            SurfaceHolder holder = getSurfaceHolder();
            Canvas canvas = holder.lockCanvas();
            canvas.drawColor(getResources().getColor(R.color.cyan_dark));//背景色
            for(int i=0;i<fireFlyList.size();i++){
                FireFly fireFly = fireFlyList.get(i);
                float ffy = fireFly.getFfy();
                float ffx = fireFly.getFfx();

                float speed = fireFly.getSpeed();
                int angle = fireFly.getAngle();
                int initAlpha = fireFly.getInitAlpha();
                int plusMinusX = fireFly.getPlusMinusX();
                int diameter = fireFly.getDiameter();
                int turns = initAlpha/15 >20?20:initAlpha/15;//光晕圈数
                long twinkleTime = fireFly.getTwinkleTime();
                boolean isShine = fireFly.isShine();

                long currentTime = System.currentTimeMillis();
                if(twinkleTime - currentTime <= 0){
                    if(isShine){
                        //逐渐亮起
                        initAlpha += 10;
                    }else {
                        //逐渐熄灭
                        initAlpha -= 10;
                    }

                    if(initAlpha <= 350){//选值大于255，延长高光时间
                        fireFly.setInitAlpha(initAlpha);
                        if(initAlpha <= fireFly.getAlpha()){
                            fireFly.setShine(true);
                            fireFly.setInitAlpha(fireFly.getAlpha());
                            fireFly.setTwinkleTime(currentTime +fireFly.getDisTime());
                        }
                    }else {
                        fireFly.setShine(false);
                    }
                    if(initAlpha > 255){
                        initAlpha = 255;
                    }
                }else if(initAlpha != fireFly.getAlpha()){
                    if(initAlpha < fireFly.getAlpha()){
                        initAlpha +=2;
                        fireFly.setInitAlpha(initAlpha);
                    }else {
                        fireFly.setInitAlpha(fireFly.getAlpha());
                    }
                }

                for(int j = 0; j< turns; j++){
                    ShapeDrawable shapeDrawable = new ShapeDrawable(new OvalShape());
                    Paint paint = shapeDrawable.getPaint();
                    paint.setAntiAlias(true);
                    shapeDrawable.getPaint().setColor(getResources().getColor(R.color.golden3));

                    if(j==0){
                        paint.setStyle(Paint.Style.FILL);
                    }else {
                        paint.setStyle(Paint.Style.STROKE);
                        paint.setStrokeWidth(strokeWidth);
                    }
                    int alpha = initAlpha - (initAlpha / turns *j);
                    paint.setAlpha(alpha);

                    Rect rect = new Rect();
                    rect.top = (int) (ffy-j);
                    rect.left = (int) (ffx-j);
                    rect.bottom = (int) (ffy+diameter+j);
                    rect.right = (int) (ffx+diameter+j);

                    shapeDrawable.setBounds(rect);
                    shapeDrawable.draw(canvas);
                }
                //Math.sqrt(n) 平方根
                //Math.sin(30x2xMath.PI/360)
                double tan = Math.tan(angle*2*Math.PI/360);
                // 1. speed = x*x + y*y ; 2. y = tan@*x -> 增量：x = speed/[(1+tan@平方)开平方]
                float mX = (float) (((double) speed)/Math.sqrt((1D+tan*tan))*plusMinusX);
                float mY = (float) (tan*mX);//增量：y
                fireFly.setFfx(ffx+mX);
                fireFly.setFfy(ffy+mY);

                float centerX = fireFly.getFfx()+fireFly.getDiameter()/2;//x坐标中心点
                float centerY = fireFly.getFfy()+fireFly.getDiameter()/2;
                if(centerX <= 0 || centerY <= 0 || centerX >= widthPixels || centerY >= heightPixels){
                    //萤火虫飞出屏幕范围后，重置基础属性
                    fireFly.changeData(mContext);
                }
            }

            holder.unlockCanvasAndPost(canvas);
        }
    }
}
